let db = require('../db/dbmanager');
var format          = require('string-format');
const log4js        = require('../data/log');
const constants = require('../data/constants');
const logger        = log4js.getLogger('db');

/**
 * 服务器信息
 */
let MediaServer={
    cache:null,
    /**
     * 插入媒体服务器
     */
    insert: function(data){
        let p = new Promise(function(resolve, reject){
            let param = {
                $server_id: data.server_id,
                $media_host: data.media_host,
                $http_port: data.http_port,
                $https_port: data.https_port,
                $rtmp_port: data.rtmp_port,
                $rtp_min_port: data.rtp_min_port,
                $rtp_max_port: data.rtp_max_port,
                $secret: data.secret
            };
            const sql = "INSERT INTO MEDIASERVER(server_id,media_host,http_port,https_port,rtmp_port,rtp_min_port,rtp_max_port,secret)VALUES($server_id,$media_host,$http_port,$https_port,$rtmp_port,$rtp_min_port,$rtp_max_port,$secret)";
    
            db.sqliteDB.run(sql,param);
            MediaServer.cache = null;
            db.sqliteDB.lastRow("DEVICE",(d)=>{
                resolve(d);
            });   
        });
        return p;
    },
    /**
     * 更新媒体服务器信息
     */
    update: function(newdata, callback){
        let sqldata = {$server_id: newdata.server_id};
        let newsql = '';
        if(newdata.media_host){
            sqldata.$media_host = newdata.media_host;
            if(newsql) newsql+=',';
            newsql += "media_host=$media_host";
        }
        if(newdata.http_port){
            sqldata.$http_port = newdata.http_port;
            if(newsql) newsql+=',';
            newsql += "http_port=$http_port";
        }
        if(newdata.https_port){
            sqldata.$https_port = newdata.https_port;
            if(newsql) newsql+=',';
            newsql += "https_port=$https_port";
        }
        if(newdata.rtmp_port){
            sqldata.$rtmp_port = newdata.rtmp_port;
            if(newsql) newsql+=',';
            newsql += "rtmp_port=$rtmp_port";
        }
        if(newdata.rtp_min_port){
            sqldata.$rtp_min_port = newdata.rtp_min_port;
            if(newsql) newsql+=',';
            newsql += "rtp_min_port=$rtp_min_port";
        }
        if(newdata.rtp_max_port){
            sqldata.$rtp_max_port = newdata.rtp_max_port;
            if(newsql) newsql+=',';
            newsql += "rtp_max_port=$rtp_max_port";
        }
        if(newdata.secret){
            sqldata.$secret = newdata.secret;
            if(newsql) newsql+=',';
            newsql += "secret=$secret";
        }
        const sql = "update MEDIASERVER set " + newsql + " where server_id=$server_id";
        
        db.sqliteDB.run(sql,sqldata);
        MediaServer.cache=null;
        if(callback){
            callback(newdata);
        }
    },
    del:function(server_id){
        let param={
            $server_id: server_id
        };
        const sql = "DELETE FROM MEDIASERVER WHERE server_id=$server_id";
        db.sqliteDB.run(sql,param);
        MediaServer.cache = null;
    },
    getById:async function(id){
        if(!MediaServer.cache){
            await MediaServer.reloadCache();
        }
        let p = new Promise(function(resolve, reject){
            let item = MediaServer.cache.find((value, index, arr)=>{
                return value.id == id
            });
            resolve(item)
        });
        return p;
    },
    getByServerId:async function(server_id, callback){
        if(!MediaServer.cache){
            await MediaServer.reloadCache();
        }
        let item = MediaServer.cache.find((value, index, arr)=>{
            return value.server_id == server_id
        });
        callback(item)
    },
    reloadCache: function(){
        let p = new Promise(function(resolve, reject){
            if(!MediaServer.cache){
                const sql = "SELECT * from MEDIASERVER order by id DESC";
                db.sqliteDB.queryData(sql, function(rows){
                    MediaServer.cache = Object.assign(rows);
                    resolve(MediaServer.cache);
                });
            }else{
                resolve(MediaServer.cache);
            }
        });
        return p;
    },
    /**
     * 查询列表
     * @param {*} page 第几页
     * @param {*} size 每页大小
     */
    list:function(page,size){

        let p = new Promise(function(resolve,reject){
            if(MediaServer.cache){
                resolve(MediaServer.cache)
            }else{
                const sql = format("SELECT * from MEDIASERVER order by id DESC limit {0} offset {0}*{1}", size, page);
                db.sqliteDB.queryData(sql,function(rows){
                    MediaServer.cache = Object.assign(rows);
                    resolve(MediaServer.cache);
                });
            }
        });
        return p;
    },
    count:function(){
        let p = new Promise(function(resolve,reject){
            let sql = "SELECT COUNT(*) as c FROM MEDIASERVER";
            db.sqliteDB.oneData(sql,(ret) => {
                resolve(ret.c)
            });
        });
        return p;
    },
    getInfoById: async function(id){
        let publicIp = await constants.publicIp();
        let p = new Promise(async function(resolve, reject){
            let item = await MediaServer.getById(id);
            if(item){
                item.local_host = item.media_host;

                // 如果在同一台电脑，可能会出现访问公网IP无法连接到端口
                // 这里强制连接本机ip
                if(publicIp == item.media_host){
                    item.local_host = '127.0.0.1';
                }
                resolve({
                    // 这个地址用来请求ZLMediaKit的API使用
                    zlk_api_host: format('http://{local_host}:{http_port}/', item),
                    url: format('http://{media_host}:{http_port}/', item),
                    urlTls : format('https://{media_host}:{https_port}/', item),
                    rtmp: format('rtmp://{media_host}:{rtmp_port}/', item),
                    rtmp_snap: format('rtmp://{local_host}:{rtmp_port}/', item),
                    secret: item.secret,
                    rtp_min_port: item.rtp_min_port,
                    rtp_max_port: item.rtp_max_port,
                    rtmp_port: item.rtmp_port

                })
            }else{
                reject()
            }
        });
        
        return p;
    },
    getInfoByServerId :async function(serverId){
        let publicIp = await constants.publicIp();
        let p = new Promise(function(resolve, reject){
            MediaServer.getByServerId(serverId, (item) => {

                if(item ){
                    item.local_host = item.media_host;

                    // 如果在同一台电脑，可能会出现访问公网IP无法连接到端口
                    // 这里强制连接本机ip
                    if(publicIp == item.media_host){
                        item.local_host = '127.0.0.1';
                    }
                    resolve({
                        // 这个地址用来请求ZLMediaKit的API使用
                        zlk_api_host: format('http://{local_host}:{http_port}/', item),
                        url: format('http://{media_host}:{http_port}/', item),
                        urlTls : format('https://{media_host}:{https_port}/', item),
                        rtmp: format('rtmp://{media_host}:{rtmp_port}/', item),
                        rtmp_snap: format('rtmp://{local_host}:{rtmp_port}/', item),
                        secret: item.secret,
                        rtp_min_port: item.rtp_min_port,
                        rtp_max_port: item.rtp_max_port,
                        rtmp_port   : item.rtmp_port,
                        media_host  : item.media_host

                    })
                }else{
                    reject('no media server,serverId='+ serverId);
                }
            })
        });
        
        return p;
    }
};

module.exports=MediaServer;